package BLC

import (
	"github.com/boltdb/bolt"
	"log"
)

const dbName  ="blockchain.db"

const blockTableName  = "blocks"

type BlockChain struct {
	Tip []byte // 最新的区块的hash
	DB *bolt.DB
}

//2 增加区块到区块链里面
/*func (blc *BlockChain) AddBlockToBlockchain(data string,height int64,priHash []byte){
	//创建新区快
	newBlock :=NewBlock(data,height,priHash)
	//往区块链添加区块
	blc.Blocks = append(blc.Blocks,newBlock)
}*/

// 1. 创建带有创世区块的区块链
func CreateBlockchainWithGenesisBlock() *BlockChain{

	// 打开数据库
	db, err := bolt.Open(dbName,0600,nil)
	if err != nil{
		log.Fatal(err)
	}
	var blockHash []byte

	err = db.Update(func(tx *bolt.Tx) error {

		// 创建表
		b := tx.Bucket([]byte(blockTableName))

		if err != nil{
			log.Panic(err)
		}

		if b == nil {
			b , err  = tx.CreateBucket([]byte(blockTableName))
			if err != nil {
				log.Panic(err)
			}

			//创建创始区块
			genesisBlock := CreateGenesisBlock("GenisisBlock Data .....")
			// 存储
			err := b.Put(genesisBlock.Hash,genesisBlock.SeriaLize())
			if err != nil {
				log.Panic(err)
			}

			// 存储最新的区块的hash
			err = b.Put([]byte("l"),genesisBlock.Hash)
			if err != nil {
				log.Panic(err)
			}

			blockHash = genesisBlock.Hash

		}

		return nil
	})



	//反回区块链对象
	return &BlockChain{blockHash,db}
}